// 和用户相关的状态管理
import { createSlice } from "@reduxjs/toolkit";
import { removeToken, request } from "@/utils";
import { setToken as _setToken, getToken } from "@/utils";
import { loginAPI, getProfileAPI } from "@/apis/user";
const userStore = createSlice({
  name: "user",
  // 初始数据
  initialState: {
    // 先看看本地有没有token
    token: getToken() || "",
    userInfo: {},
  },
  // 同步修改方法
  reducers: {
    setToken(state, action) {
      state.token = action.payload;
      // 存到本地
      _setToken(action.payload);
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload;
    },
    // 清除用户信息
    clearUserInfo(state) {
      state.token = "";
      state.userInfo = {};
      removeToken();
    },
  },
});
// 解构出actionCreater
const { setToken, setUserInfo, clearUserInfo } = userStore.actions;
const userReducer = userStore.reducer;
// 封装异步方法完成登录，获取token
const fetchlogin = (loginForm) => {
  return async (dispatch) => {
    //1 发送异步请求
    const res = await loginAPI(loginForm);
    // 2提交同步action进行token 存入
    dispatch(setToken(res.data.token));
  };
};
// 获取个人用户信息异步方法
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await getProfileAPI();
    dispatch(setUserInfo(res.data));
  };
};
export { setToken, fetchlogin, fetchUserInfo, clearUserInfo };
export default userReducer;
